package hyl.base.medium.Filter;

import static org.bytedeco.opencv.global.opencv_imgproc.COLOR_BGRA2GRAY;

import java.awt.image.BufferedImage;
import java.io.File;

import org.bytedeco.opencv.global.opencv_imgproc;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_core.Rect;
import org.bytedeco.opencv.opencv_core.RectVector;
import org.bytedeco.opencv.opencv_core.Scalar;
import org.bytedeco.opencv.opencv_objdetect.CascadeClassifier;

import hyl.base.medium.ImageFrame;
import hyl.base.medium.MyImage;
import hyl.core.run.IFilter;

public class FaceFilter implements IFilter<BufferedImage> {

	static final String lbpcascade_frontalface_improved = "data/lbpcascade_frontalface_improved.xml";
	static final String haarcascade_frontalcatface = "data/haarcascade_frontalcatface.xml";

	static final String lbpcascade_frontalface = "data/lbpcascade_frontalface.xml";

	static final String haarcascade_frontalface_alt = "data/haarcascade_frontalface_alt.xml";
	// 找猫脸
	static final String lbpcascade_frontalcatface = "data/lbpcascade_frontalcatface.xml";
	static final String haarcascade_frontalface_default = "data/haarcascade_frontalface_default.xml";
	CascadeClassifier face_cascade = null;

	public FaceFilter(int width, int height) {
		iframe = new ImageFrame("test", width, height);
		File fileAbsolutePath = new File(
				ClassLoader.getSystemClassLoader().getResource(haarcascade_frontalface_default).getFile());
		face_cascade = new CascadeClassifier(fileAbsolutePath.getAbsolutePath());
	}

	ImageFrame iframe = null;

	@Override
	/**
	 * 返回true 表示关闭遍历 false 表示可继续遍历
	 */
	public boolean where(BufferedImage img) {
		if (iframe == null || img == null) {
			// System.out.println("关闭了0");
			return true;
		}
		RectVector faces = new RectVector();
		org.bytedeco.opencv.opencv_core.Mat mat = MyImage.Img2Mat(img);
		Mat videoMatGray = new Mat();
		opencv_imgproc.cvtColor(mat, videoMatGray, COLOR_BGRA2GRAY);
		opencv_imgproc.equalizeHist(videoMatGray, videoMatGray);

		face_cascade.detectMultiScale(videoMatGray, faces);
		for (int i = 0; i < faces.size(); i++) {
			Rect face = faces.get(i);
			opencv_imgproc.rectangle(mat, face, Scalar.RED, 4, 8, 0);
		}
		BufferedImage img2 = MyImage.Mat2Img(mat);
		// System.out.println("d3_3_2");
		iframe.f显示(img2);
		return false;
//		if (iframe.f显示(img)) {		
//			return false;
//		}
//		else {
//			//System.out.println("关闭了0_3");
//			return true;
//		}
	}

}
